package com.colabo.j2ee.web.oaf.security.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;


public class ResourceDefinerServiceImpl extends DefaultServiceImpl implements FilterInvocationSecurityMetadataSource {
	private String uncheckSource;

	public String getUncheckSource() {
		return uncheckSource;
	}

	public void setUncheckSource(String uncheckSource) {
		this.uncheckSource = uncheckSource;
	}

	public Collection<ConfigAttribute> getAttributes(Object object) {
		String url = ((FilterInvocation) object).getRequestUrl();
		if (url.lastIndexOf('?') >= 0) {
			url = url.substring(0, url.lastIndexOf('?'));
		}
		if (isUncheckResource(url)) {
			return null;
		}

		List confDef = new ArrayList();
		while (url.length() > 0) {
			confDef.add(new SecurityConfig(url));
			if (url.lastIndexOf('/') >= 0) {
				url = url.substring(0, url.lastIndexOf('/'));
			} else {
				url = "";
			}
		}

		HttpServletRequest req = ((FilterInvocation) object).getHttpRequest();
		Map parameterMap = req.getParameterMap();
		for (Iterator it = parameterMap.keySet().iterator(); it.hasNext();) {
			String key = it.next().toString();
			confDef.add(new SecurityConfig(key + "=" + parameterMap.get(key)));
		}
		return confDef;
	}

	private boolean isUncheckResource(String url) {
		String[] uncheckResource = getUncheckSource().split(",");
		for (int i = 0; i < uncheckResource.length; i++) {
			if (url.endsWith(uncheckResource[i].trim())) {
				return true;
			}
		}
		return false;
	}

	public Iterator getConfigAttributeDefinitions() {
		return new ArrayList().iterator();
	}

	public boolean supports(Class<?> clazz) {
		return clazz.isAssignableFrom(FilterInvocation.class);
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		// TODO make sure getAllConfigAttributes doesnt affect
		return null;
	}

}
